import {promptBox, toast} from 'nc-lightapp-front';
import {formatDate, getAppPageConfig, saveValidate} from "src/hrpub/common/utils/utils";
import {getSignStatus} from "./commonFun";

const {pagecode} = getAppPageConfig()

export default class HeaderAction {
    constructor(comp) {
        this.comp = comp;
    }

    /**
     * @desc: 返回及取消按钮事件回调
     * @param {type}
     * @return:
     */
    clickBackBtn = () => {
        const {dispatch, myLeave, editTable, meta: metas, form} = this.comp.props;
        let activeTab = myLeave.activeTab
        let tableCode = myLeave.activeTab + '_list';
        if (myLeave.isEdit) {
            promptBox(
                {
                    color: "warning",
                    title: myLeave.json['6040-00005'], /* 国际化处理： 提示*/
                    content: myLeave.json['6040-00006'], /* 国际化处理： 你确定要返回吗？*/
                    beSureBtnClick: () => {
                        dispatch({
                            type: 'myLeave/update',
                            payload: {
                                showMode: 'list',
                                isEdit: false,
                                headerTitle: myLeave.json['6040-00007'], //假勤申请
                                customTemplateItemKeys: [],
                            }
                        })
                    }
                })
        } else {
            dispatch({
                type: 'myLeave/update',
                payload: {
                    showMode: 'list',
                    headerTitle: myLeave.json['6040-00007'], //假勤申请
                    customTemplateItemKeys: [],
                }
            })
            dispatch({
                type: 'myLeave/queryListAction',
                payload: {
                    key: activeTab,
                    beginDate: myLeave.beginValue,
                    endDate: myLeave.endValue
                }
            }).then(res => {
                if (res.success) {
                    if (res.data) {
                        editTable.setTableData(tableCode, res.data[tableCode])
                        dispatch({
                            type: 'myLeave/update',
                            payload: {
                                [activeTab + 'PageInfo']: res.data[tableCode].pageInfo
                            }
                        })
                    } else {
                        editTable.setTableData(tableCode, {rows: []})
                        dispatch({
                            type: 'myLeave/update',
                            payload: {
                                [activeTab + 'PageInfo']: Object.assign({}, myLeave[activeTab + 'PageInfo'], {total: null})
                            }
                        })
                    }
                }
            })
        }
    }
    /**
     * @desc: 按钮时间注册回调函数
     * @param {type}
     * @return:
     */
    headerButtonClick = async (props, btncode) => {
        const {dispatch, myLeave, form} = this.comp.props
        const {setFormStatus, setAllFormValue, EmptyAllFormValue} = form

        let formCode = myLeave.activeTab + '_card'
        let tableCode = myLeave.activeTab + '_list'
        switch (btncode) {
            // 新增按钮  初始化 pk 默认数据
            case 'head_batch_add':
                this.addBatchAttend()
                break;
            case 'head_free_add':
                this.addFreeAttend()
                break;
            case 'head_cancel':
                this.clickBackBtn();
                break;
            case 'head_query':
                dispatch({
                    type: 'myLeave/update',
                    payload: {
                        [myLeave.activeTab + 'PageInfo']: Object.assign({}, myLeave[myLeave.activeTab + 'PageInfo'], {
                            pageIndex: 1
                        })
                    }
                })
                this.searchAction(myLeave.activeTab, tableCode);
                break;
            case 'head_save':
                this.batchSaveBill(myLeave.activeTab, formCode)
                break;
            case 'head_submit':
                this.batchSubmitBill(myLeave.activeTab, formCode)
                break;
            case 'head_refresh':
                this.searchAction(myLeave.activeTab, tableCode);
                break;
            case 'head_file':
                this.showUploader();
                break;
            case 'head_edit':
                this.editAction(formCode);
                break;
            case 'head_delete':
                this.deleteAction(myLeave.activeTab, formCode);
                break;
        }
    }

    addBatchAttend = () => {
        const {dispatch} = this.comp.props

        dispatch({
            type: 'myLeave/update',
            payload: {
                batchModalVisible: true,
                isFreeAdd: false
            }
        })
    }

    addFreeAttend = () => {
        let formCode = 'attendance_card'
        const {dispatch, myLeave, form, editTable, meta} = this.comp.props
        const {
            setFormStatus,
            setAllFormValue,
            EmptyAllFormValue,
            getFormItemsValue,
            setItemsVisible,
            setFormItemsDisabled,
            setFormItemsRequired
        } = form
        const {
            setColEditableByKey
        } = editTable;
        EmptyAllFormValue(formCode)
        let cardDefaultVisiable = {
            fill_date: false,
            original_sign_status: false,
            original_sign_time: false,
            fill_time: false
        }
        let cardDefaultDisabled = {
            pk_attend_staff: false
        }
        let cardDefaultRequired = {
            fill_type_id: true
        }
        setItemsVisible(formCode, cardDefaultVisiable);
        setFormItemsDisabled(formCode, cardDefaultDisabled);
        setFormItemsRequired(formCode, cardDefaultRequired);
        setColEditableByKey('batch_attend_edit_list', 'fillDate', false)
        editTable.setTableData('batch_attend_edit_list', {rows: []});
        let temp = meta.getMeta();
        temp['batch_attend_edit_list'].items.forEach(item => {
            if (item.attrcode === "originalSignTime") {
                item.visible = false
            }
        });
        meta.setMeta(temp);
        temp = null
        cardDefaultVisiable = null
        cardDefaultDisabled = null
        dispatch({
            type: 'myLeave/update',
            payload: {
                showMode: 'card',
                isEdit: true,
                batchModalVisible: false,
                isFreeAdd: true,
                headerTitle: myLeave.subTitle
            }
        })
        dispatch({
            type: 'myLeave/AddAction',
            payload: {
                key: myLeave.activeTab,
                operat: 0
            }
        }).then(res => {
            setAllFormValue({[formCode]: res.data[formCode]});
            let billId = getFormItemsValue(formCode, 'pk_' + myLeave.activeTab).value;
            let approvestatus = getFormItemsValue(formCode, 'approvestatus').value;
            dispatch({
                type: 'myLeave/update',
                payload: {
                    billId,
                    approvestatus
                }
            })
        })
        setFormStatus(formCode, 'add')
        editTable.setStatus('batch_attend_edit_list', 'edit')
    }
    /**
     * @desc: 表头点击修改事件触发
     * @param {type}
     * @return:
     */
    editAction = (formCode) => {
        const {dispatch, form, editTable, meta, myLeave} = this.comp.props;
        form.setFormStatus(formCode, 'edit');
        editTable.setStatus('batch_attend_edit_list', 'edit');
        editTable.setColEditableByKey('batch_attend_edit_list', 'fillDate', !myLeave.isFreeAdd)
        let temp = meta.getMeta();
        let tempForm = form.getAllFormValue(formCode);
        let pk_attend_staff = tempForm.rows[0].values.pk_attend_staff && tempForm.rows[0].values.pk_attend_staff.value
        temp[formCode].items.forEach(item => {
            if (item.attrcode === "fill_type_id") {
                item.queryCondition = function () {
                    return {
                        pk_attend_staff: pk_attend_staff
                    }
                }
            }
        });
        meta.setMeta(temp);
        dispatch({
            type: 'myLeave/update',
            payload: {
                isEdit: true
            }
        })
    }

    /**
     * @desc: 单据删除事件触发
     * @param {type}
     * @return:
     */
    deleteAction = (activeTab, formCode) => {
        const {dispatch, myLeave} = this.comp.props
        const pk = myLeave.billId
        promptBox({
            color: "warning",
            title: myLeave.json['6040-00005'], /* 国际化处理： 提示*/
            content: myLeave.json['6040-000060'],
            beSureBtnClick: () => {
                dispatch({
                    type: 'myLeave/deleteAction',
                    payload: {
                        activeTab,
                        pk
                    }
                }).then(res => {
                    if (res.success) {
                        toast({
                            color: 'success',
                            content: myLeave.json['6040-000012']
                        })
                        this.clickBackBtn();
                    }
                })
            }
        })
    }
    searchAction = async (key, tableCode) => {
        const {dispatch, myLeave} = this.comp.props;
        let res = await dispatch({
            type: 'myLeave/queryListAction',
            payload: {
                key,
                beginDate: myLeave.beginValue,
                endDate: myLeave.endValue
            }
        })
        if (res.success) {
            if (res.data) {
                this.handleListData(res.data[tableCode], tableCode)
            } else {
                this.handleListData({rows: [], pageInfo: {pageIndex: "1", pageSize: "10", total: null}}, tableCode)
            }
        }
    }
    /**
     * @desc: 数据请求完后处理函数封装
     * @param {type}
     * @return:
     */
    handleListData = (data, tableCode) => {
        const {dispatch, myLeave, editTable} = this.comp.props
        editTable.setTableData(tableCode, data)
        dispatch({
            type: 'myLeave/update',
            payload: {
                [myLeave.activeTab + 'PageInfo']: data.pageInfo
            }
        })
    }
    /**
     * @desc: 表单校验
     * @param {type}
     * @return:
     */
    checkBill = (formCode) => {
        const {dispatch, myLeave, form} = this.comp.props;
        const {isCheckNow} = form;
        return isCheckNow(formCode, 'warning')
    }

    batchSaveBill = (key, formCode, submitFn) => {
        const {dispatch, myLeave, form, editTable} = this.comp.props
        const {json = {}} = myLeave;
        if (!this.checkBill(formCode)) {
            return;
        }
        const checkRows = editTable.getAllData('batch_attend_edit_list')
        const requireFlag = editTable.checkRequired('batch_attend_edit_list', checkRows.rows);
        if (!requireFlag) {
            return;
        }
        let tempForm = form.getAllFormValue(formCode);
        let attendData = []
        checkRows.rows.forEach(row => {
            let value = row.values
            let fillDate = typeof value.fillDate.value === 'number' ? formatDate(value.fillDate.value) : formatDate(new Date(value.fillDate.value))
            let temp = {
                "originalSignTime": value.originalSignTime && value.originalSignTime.value
                    ? new Date(value.originalSignTime.value).getTime() : '',
                "signTime": value.signTime && value.signTime.value,
                "fillDate": fillDate,
                "fillTime": new Date(fillDate + " " + value.fillTime.value).getTime(),
                "listOrder": value.listOrder ? value.listOrder.value : "-1",
                "originalSignStatus": value.signState && value.signState.value,
                "fill_reason": value.fill_reason && value.fill_reason.value
            }
            attendData.push(temp)
        })
        tempForm.rows[0].values.fill_details = {value: JSON.stringify(attendData)}

        let formData = {
            model: tempForm
        }

        saveValidate(this.comp.props, pagecode, formCode, null, 'form', null).then(() => {
            let durationObject = myLeave.durationObject
            dispatch({
                type: 'myLeave/saveBillAction',
                payload: {
                    key,
                    formData,
                    formCode,
                    durationObject
                }
            }).then(res => {
                if (res.success) {
                    form.setFormStatus(formCode, 'browse');
                    editTable.setStatus('batch_attend_edit_list', 'browse')
                    if (res.data && res.data[formCode]) {
                        form.setAllFormValue({
                            [formCode]: res.data[formCode]
                        })
                        let batch_attend_list = {
                            areacode: 'batch_attend_edit_list',
                            rows: []
                        }
                        if (res.data[formCode].rows[0] && res.data[formCode].rows[0].values.fill_details
                            && res.data[formCode].rows[0].values.fill_details.value) {
                            let tempData = JSON.parse(res.data[formCode].rows[0].values.fill_details.value)
                            tempData.forEach((item, index) => {
                                let values = {
                                    fillDate: {
                                        value: item['fillDate']
                                    },
                                    fillTime: {
                                        value: formatDate(item['fillTime'], ':', 'hh-mm')
                                    },
                                    originalSignTime: {
                                        value: item['originalSignTime'] ? formatDate(item['originalSignTime'], ' ', 'y-m-d-h-m'): ''
                                    },
                                    listOrder: {
                                        value: item['listOrder']
                                    },
                                    isNeedFill: {
                                        value: ''
                                    },
                                    signState: {
                                        value: item['originalSignStatus'],
                                        display: getSignStatus(item['originalSignStatus'], json)
                                    },
                                    originalSignStatus: {
                                        value: item['originalSignState']
                                    },
                                    fillStatus: {
                                        value: ''
                                    }
                                };
                                batch_attend_list.rows.push({
                                    status: '0',
                                    values
                                })
                            })
                        }
                        editTable.setTableData('batch_attend_edit_list', batch_attend_list);
                    }
                    dispatch({
                        type: 'myLeave/update',
                        payload: {
                            isEdit: false
                        }
                    });
                    if (typeof (submitFn) === 'function') {
                        submitFn()
                    }
                }
            })
        })
    }

    batchSubmitBill = (key, formCode) => {
        const {form} = this.comp.props;
        const {getFormItemsValue} = form;
        let pkKey = 'pk_' + key;
        let pk = getFormItemsValue(formCode, pkKey).value;
        this.batchSaveBill(key, formCode, () => {
            this.submitFn(key, pk)
        })
    }

    submitFn = (key, pk) => {
        const {dispatch, myLeave} = this.comp.props;
        dispatch({
            type: 'myLeave/submitBillAction',
            payload: {
                key,
                pk
            }
        }).then(res => {
            if (res.success) {
                if (res.data && res.data.content) {
                    dispatch({
                        type: 'myLeave/update',
                        payload: {
                            assignedData: res.data.content,
                            assignedDisplay: true
                        }
                    })
                } else {
                    toast({
                        color: 'success',
                        content: myLeave.json['6040-00004']  // 提交成功！
                    });
                    this.clickBackBtn();
                }
            }
        })
    }

    /**
     * @desc: 显示附件管理
     * @param {type}
     * @return:
     */
    showUploader = (ev) => {
        const {dispatch} = this.comp.props;
        dispatch({
            type: 'myLeave/update',
            payload: {
                showUploader: true
            }
        })
    }
    onBeginValueChange = (date) => {
        const {dispatch} = this.comp.props;
        dispatch({
            type: 'myLeave/update',
            payload: {
                beginValue: date
            }
        })
    }

    onEndValueChange = (date) => {
        const {dispatch} = this.comp.props;
        dispatch({
            type: 'myLeave/update',
            payload: {
                endValue: date
            }
        })
    }

    // 单据指派
    assignedBill = (value) => {
        const {dispatch, myLeave, form} = this.comp.props;
        const {getFormItemsValue} = form;
        let key = myLeave.activeTab
        let pkKey = 'pk_' + key;
        let formCode = key + '_card'
        let pk = getFormItemsValue(formCode, pkKey).value;
        dispatch({
            type: 'myLeave/submitBillAction',
            payload: {
                key,
                pk,
                content: value
            }
        }).then(res => {
            if (res.success) {
                toast({
                    color: 'success',
                    content: myLeave.json['6040-00004']  // 提交成功！
                });
                dispatch({
                    type: 'myLeave/update',
                    payload: {
                        assignedDisplay: false,
                        assignedData: null
                    }
                })
                this.clickBackBtn();
            }
        })
    }
    cancelAssigned = () => {
        const {dispatch} = this.comp.props;
        dispatch({
            type: 'myLeave/update',
            payload: {
                assignedDisplay: false,
                assignedData: null
            }
        })
    }

    didUpdate = () => {
        const {button, myLeave} = this.comp.props
        let canEdit = myLeave.approvestatus === '-1'
        let canSubmit = myLeave.approvestatus === '-1'
        button.setButtonsVisible({
            head_edit: myLeave.showMode === 'card' && !myLeave.isEdit && canEdit,
            head_query: myLeave.showMode === 'list',
            head_refresh: myLeave.showMode === 'list',
            head_file: myLeave.showMode === 'card',
            head_save: myLeave.showMode === 'card' && myLeave.isEdit,
            head_submit: myLeave.showMode === 'card' && canSubmit,
            head_cancel: myLeave.showMode === 'card' && myLeave.isEdit && canEdit,
            head_delete: myLeave.showMode === 'card' && !myLeave.isEdit && canSubmit,
            list_delete: myLeave.showMode === 'card' && !myLeave.isEdit,
            list_withdraw: myLeave.showMode === 'list',
            list_submit: myLeave.showMode === 'list',
            head_batch_add: myLeave.showMode === 'list',
            head_free_add: myLeave.showMode === 'list'
        })
    }
}